package cn.itcast.web.action;


import cn.itcast.domain.system.User;
import cn.itcast.service.UserService;
import cn.itcast.web.action.common.BaseAction;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.util.List;

@Namespace("/")
@ParentPackage("json-default")
@Controller
@Scope("prototype")
@Actions
public class UserAction extends BaseAction<User> {
    @Autowired
    private UserService userService;

    @Action(value = "user_login", results = {@Result(name = "login", location = "login.html", type = "redirect"),
            @Result(name = "success", location = "index.html", type = "redirect")})
    public String login() {
        //基于shiro实现登陆
        //创建subject(代理user)

        Subject subject = SecurityUtils.getSubject();

        //创建用户的token(封装user登录信息)

        AuthenticationToken token = new UsernamePasswordToken(model.getUsername(), model.getPassword());
        try {
            subject.login(token);
            //登录成功
            return SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            //登录失败
            return LOGIN;
        }
    }

    //location.href = './user_logout.action';
    @Action(value = "user_logout", results = {@Result(name = "success", location = "login.html", type = "redirect")})
    public String logout() {
        //基于shiro注销用户
        //shiro 框架会自动将subject信息存入session
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return SUCCESS;
    }

    //url: ../../user_list.action 查询全部 返回json
    @Action(value = "user_list", results = {@Result(name = "success", type = "json")})
    public String findAll() {
        List<User> users = userService.findAll();
        ServletActionContext.getContext().getValueStack().push(users);

        return SUCCESS;
    }
    // ../../user_save.action roleIds
    private String[] roleIds;

    public void setRoleIds(String[] roleIds) {
        this.roleIds = roleIds;
    }
    @Action(value = "user_save",results = {
            @Result(name = "success",type="redirect",location = "pages/system/userlist.html")})
    public String save(){
        userService.save(model,roleIds);
        return SUCCESS;
    }
}
